<template>
  <!--订房订单-->
  <el-card> <el-row gutter="40">
      <el-col :span="6">
        <el-date-picker v-model="value1" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" :size="size" @change="handleRegionChange" />
      </el-col>
      <el-col :span="6">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
        </el-form>
      </el-col>
      <el-col :span="4">
        <el-select v-model="formInline.region" clearable placeholder="请选择" value="-1" @change="handleRegionChange">
          <el-option label="全部房型" value="-1" />
          <el-option v-for="item in RoomList" :key="item.Rtid" :label="item.Rtname" :value="item.Rtid" />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-form-item>
          <el-input v-model="formInline.user" placeholder="顾客姓名/手机号/订单号" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-form-item>
          <el-button type="primary" @click.prevent="handleRegionChange">搜索</el-button>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="4">
        <el-select v-model="formInline.Payment" clearable placeholder="请选择" @change="handleRegionChange">
          <el-option label="全部付费类型" value="-1" />
          <el-option v-for="item in PaymentTable" :key="item.Id" :label="item.Value" :value="item.Id" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="formInline.ordertypes" clearable placeholder="请选择" @change="handleRegionChange">
          <el-option label="全部订单类型" value="-1" />
          <el-option v-for="item in ordertypesTable" :key="item.Id" :label="item.Value" :value="item.Id" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-form-item label="">
          <el-select v-model="formInline.orderstatus" clearable placeholder="请选择" @change="handleRegionChange">
            <el-option label="全部状态" value="-1" />
            <el-option v-for="item in orderstatusTable" :key="item.Id" :label="item.Value" :value="item.Id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6" style="text-align: right">
        <el-form-item>
          <el-button type="primary" @click.prevent="exportExcel()">导出</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-card>
  <el-card>
    <div>
      <el-row>
        <el-col :span="40">
          <el-table :data="tableData">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="OrderNo" label="订单编号" width="120" />
            <el-table-column prop="Rtname" label="房型(房号)" width="120" />
            <el-table-column prop="CName" label="房客姓名" width="120" />
            <el-table-column prop="Tel" label="房客手机号" width="120" />
            <el-table-column prop="EntryTime" label="入住时间" width="120" />
            <el-table-column prop="LeaveTime" label="离店时间" width="120" />
            <el-table-column prop="" label="实际付款" width="120">
              <template v-slot="scope">
                ￥<span style="color: red">{{ calculateTotalPrice(scope.row.EntryTime, scope.row.LeaveTime,
        scope.row.ActualPay) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="状态" width="120" />
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="small" type="danger" @click="handleDelete(scope.row.Id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <table style="margin: 5px auto;">
            <tbody>
              <tr>
                <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                    :page-sizes="[1, 2, 3, 10]" layout="total, slot,sizes" :total="pager.totalCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                    next-text="下一页">
                    <span class="el-pagination__total is-first">&nbsp;共计{{ pager.pageCount }}页,当前{{
        pager.pageIndex
      }}/{{ pager.pageCount }}页</span>
                  </el-pagination>
                </td>
                <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                    :page-sizes="[1, 2, 3, 10]" layout="slot, prev, pager" :total="pager.totalCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                    next-text="下一页">
                    <button @click="handleCurrentChange(1)" :disabled="pager.pageIndex == 1"
                      class="btn-prev">首页</button>
                  </el-pagination></td>
                <td><el-pagination v-model:current-page="pager.pageIndex" v-model:page-size="pager.pageSize"
                    :page-sizes="[1, 2, 3, 10]" layout="slot, next, jumper" :total="pager.totalCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                    next-text="下一页">
                    <button @click="handleCurrentChange(pager.pageCount)" :disabled="pager.pageIndex == pager.pageCount"
                      class="next-prev">尾页</button>
                  </el-pagination></td>
              </tr>
            </tbody>
          </table>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>
<script lang="ts" setup>
const size = ref<"default" | "large" | "small">("default");
const value1 = ref("");
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
]
import { ElTable } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';

interface User {
  date: string;
  name: string;
  address: string;
}
const formInline = reactive({
  user: "",
  region: "-1",
  Payment: "-1",
  ordertypes: "-1",
  orderstatus: "-1",
});
const RoomList = ref([{ Rtid: Number, Rtname: String }]);
const PaymentTable = ref([{ Id: Number, Value: String }]);
const ordertypesTable = ref([{ Id: Number, Value: String }]);
const orderstatusTable = ref([{ Id: Number, Value: String }]);
const pager = {
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const toggleSelection = (rows?: User[]) => {
  if (rows) {
    rows.forEach((row) => // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      multipleTableRef.value!.toggleRowSelection(row, undefined));
  } else {
    multipleTableRef.value!.clearSelection();
  }
};
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val;
};
//consttableData=reactive<IOrderInfo[]>([])
  //axios.defaults.baseURL = 'http://10.31.59.9:9033/api/';//设置请求的根路径
function exportExcel() {
  axios({
    method: "get",
    url: "http:localhost:5003/api/OrderInfo/DownloadExcel",
    data: {},
    //设置请求头的 Content-Type 为 “application/json;charset=UTF-8”
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
    },
    //设置响应的 responseType 为 “blob”，表示返回的数据是二进制数据
    responseType: "blob",
  })
    .then((res) => {
      console.log(res, "res");
      //创建一个 Blob 对象来存储数据
      const blob = new Blob([res.data]);
      //使用 URL.createObjectURL() 方法生成一个 URL，指向这个 Blob 对象
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      //创建一个<a>标签，设置其href属性为这个URL，download属性为要下载的文件名
      link.download = "订房订单数据导出.xlsx";
      //触发<a>标签的点击事件
      link.click();
      //URL.revokeObjectURL()方法释放这个URL对象
      URL.revokeObjectURL(url);
    })
    .catch((err) => { });
}
const tableData = ref([])

function calculateTotalPrice(EntryTime: string, LeaveTime: string, ActualPay: number) {
  const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const entryDate = new Date(EntryTime).getTime();
  const leaveDate = new Date(LeaveTime).getTime();
  const totalDays = Math.round(Math.abs((entryDate - leaveDate) / oneDay)) + 1;
  return (totalDays * ActualPay).toFixed(2);
}
function OrderInfoShow() {
  axios.get("http:localhost:5003/api/OrderInfo/OrderInfoShow", {
    params: {
      pageIndex: pager.pageIndex,
      pageSize: pager.pageSize,
      StartTime: value1.value[0],
      EndTime: value1.value[1],
      Name: formInline.user,
      RTid: formInline.region,    
      paymenttypesId: formInline.Payment,
      ordertypes: formInline.ordertypes,
      orderStatus: formInline.orderstatus,
    }
  }).then(res => {
    tableData.value = res.data.Data;
    pager.totalCount = res.data.TotalCount;
    pager.pageCount = res.data.PageCount;
  })
}
const handleDelete = (Id: number) => {
  ElMessageBox.confirm(
    '确认删除订单?',
    '订单删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post(`http:localhost:5003/api/OrderInfo/Delete1?id=${Id}`).then(res => {
        if (res.data.Code == 200) {
          ElMessage.success('删除成功');
          OrderInfoShow();
        } else {
          ElMessage.error('删除失败');
          return;
        }
      })
    })
    .catch(() => {
    })
}

function DicShow() {
  axios
    .get("http:localhost:5003/api/Dic/DicShow?Identification=paymenttypes")
    .then((res) => {
      PaymentTable.value = res.data;
    });
}
function ordertypesShow() {
  axios
    .get("http:localhost:5003/api/Dic/DicShow?Identification=ordertypes")
    .then((res) => {
      ordertypesTable.value = res.data;
    });
}
function orderstatusShow() {
  axios
    .get("http:localhost:5003/api/Dic/DicShow?Identification=orderstatus")
    .then((res) => {
      orderstatusTable.value = res.data;
    });
}
const handleRegionChange = () => {
  OrderInfoShow(); // 当房型选择改变时，调用 OrderInfoShow 函数
};
function AddHttpClient() {
  axios.get("http:localhost:5003/api/OrderInfo/AddHttpClient").then((res) => {
    RoomList.value = res.data;
  });
}
function handleSizeChange(size: number) {
  pager.pageSize = size;
  OrderInfoShow();
}
function handleCurrentChange(index: number) {
  pager.pageIndex = index;
  OrderInfoShow();7
}
onMounted(() => {
  OrderInfoShow();
  AddHttpClient();
  DicShow();
  ordertypesShow();
  orderstatusShow();
});
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 260px;
}

.demo-form-inline .el-select {
  --el-select-width: 260px;
}

.group {
  width: 200px;
}
</style>
